// useReducer的使用方法

import { useReducer } from "react"

// 1.定义reducer函数，根据不同的action 返回不同的状态
function reducer(state, action) {
  switch (action.type) {
    case "INC":
      return state + 1
    case "DEC":
      return state - 1
    case "SET":
      return action.payload
    default:
      return state
  }
}
function App() {
  // 2.组件调用useReducer(reducer, 0) => [state, dispatch]
  // useReducer函数里传入上面定义好的reducer函数和初始状态0，
  // 返回一个数组，数组中第一个元素是状态，第二个元素是dispatch函数，修改初始状态只能使用dispatch函数
  const [state, dispatch] = useReducer(reducer, 0)
  return (
    <div>
      {/* 3.调用dispatch({type: "INC"}) => 通知reducer产生一个新的状态，使用这个状态更新UI */}
      <button onClick={() => dispatch({ type: "DEC" })}>-</button>
      {state}
      <button onClick={() => dispatch({ type: "INC" })}>+</button>
      <button onClick={() => dispatch({ type: "SET", payload: 100 })}>To 100</button>
    </div>
  )
}


export default App